﻿/**********************************************
 * 功能名称：作业中心向目标中间体分配动因录入页面
编写人：  杨莹
建立时间： 杨 2012年07月11日
说明：
加载页面时，列出当前操作员的责任范围的作业中心列表。
查询出选择的作业中心对应的目标产品的动因量。
 * 录入后，提交保存。

 **************************************************************/

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using Hisun.Controllers;
using System.Text;
using System.Collections.Generic;


namespace Hisun.View.CostDriver
{
    public partial class CostDriverFromCenterToPIPInput : AbcPageBase
    {
        HisunDBDataContext db = new HisunDBDataContext();
        public string alert;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {


                var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
                DropDownList_CostCenter.Items.Clear();

                FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID));

                HiddenField_CurrentCenterId.Value = "";

            }
        }

        //查询当前操作员对应的作业中心列表
        private void FillData2DropDownList(int CenterID)
        {
            ChildCenterList myCenter = new ChildCenterList(CenterID);

            var myCenterFilters = myCenter.CostCenterlist.Where(p => p.类型 == "A" && p.停用 == false && p.是否直接成本 == true);


            foreach (var MylistItem in myCenterFilters)
            {
                if (MylistItem.作业中心名称.Contains(TextBox_FilterText.Text))
                {
                    ListItem InsertItem = new ListItem(MylistItem.作业中心名称, MylistItem.作业中心ID.ToString());
                    DropDownList_CostCenter.Items.Add(InsertItem);
                }
            }


        }

        protected void Button_fullCenterList_Click(object sender, EventArgs e)
        {
            var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
            DropDownList_CostCenter.Items.Clear();
            ListItem InsertItem = new ListItem("请选择", "");
            DropDownList_CostCenter.Items.Add(InsertItem);
            FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID));

            HiddenField_CurrentCenterId.Value = "";
        }



        protected void Button_Query_Command(object sender, CommandEventArgs e)
        {
            //绑定数据
            if (DropDownList_CostCenter.SelectedValue == "")
            {
                Response.Write("<script>alert('无作业中心');</script>");
                HiddenField_CurrentCenterId.Value = "";
                HiddenField_FullDriverId.Value = "0";
                return;
            }
            HiddenField_CurrentCenterId.Value = DropDownList_CostCenter.SelectedValue;
            
            MyDataBind(HiddenField_CurrentCenterId.Value);
            if (GridView_DriverList.Rows.Count == 0)
            {
                Panel_GridList.Visible = false;

            }
            else
            {
                Panel_GridList.Visible = true;

            }
        }


        private void MyDataBind(string SelectCenterId)
        {
            int MyCenterId = Convert.ToInt32(SelectCenterId);
            var MyDataQuery = from a in db.TABC_JS_CostCenterToPIPPathFramework
                              join c in db.TABC_DM_CostDivers on a.成本动因ID equals c.成本动因ID
                              join d in db.TABC_JS_CostCenter on a.目标中心ID equals d.作业中心ID
                              join f in db.TABC_JS_ProductInProcess on a.中间体ID equals f.中间体ID
                              join g in db.TABC_JS_Product on f.产品ID equals g.产品账户ID
                              join b in
                                  (from e in db.TABC_JS_CostCenterToPIPPathDriver where e.会计期间ID == Application["accountPeriod"].ToString() && e.作业中心ID == MyCenterId select e)
                                    on a.中间体ID equals b.中间体ID into mytemp
                              where a.作业中心ID == MyCenterId && f.可用 == true  orderby f.产品ID
                              from temp in mytemp.DefaultIfEmpty()
                              select new
                              {
                                  a.ID,
                                  f.产品ID,
                                  d.作业中心ID,
                                  d.作业中心名称,
                                  a.中间体ID,
                                  f.中间体名称,
                                  g.产品账户名称,
                                  a.系数,
                                  动因量 = (temp == null ? 0 : temp.动因量),
                                  a.填充码


                              };
            GridView_DriverList.DataSource = MyDataQuery;
            GridView_DriverList.DataBind();

            HiddenField_FullDriverId.Value = (MyDataQuery.First().填充码 == null? "0":MyDataQuery.First().填充码.ToString());

            switch (HiddenField_FullDriverId.Value)
            {
                case "1":
                    {
                        //填充当前目标成本账户的原材料投入数

                        Label_FullDriver.Text = "动因量自动填充方式:" + "原材料金额";

                    
                        break;
                    }
                case "2":
                    {
                        //填充当前目标中间体的人工投入数
                        Label_FullDriver.Text = "动因量自动填充方式:" + "人工费";
                     
                        break;
                    }
                case "0":
                    {
                        Label_FullDriver.Text = "动因量自动填充方式:" + "无";
                      
                        break;
                    }



            }


        }


        //自动填充动因量数据。
        protected void Button_FullDriver_Click(object sender, EventArgs e)
        {
            int MyGridViewListCount  = GridView_DriverList.Rows.Count;
            string Ap = Application["accountPeriod"].ToString();

            if (MyGridViewListCount == 0)
            {
                alert = "<script>alert('无目标中间体数据');</script>";
                return;
            }

               //对当前列表的中间体动因记录进行插入
            for (int i = 0; i < MyGridViewListCount; i++)
            {
                GridViewRow myrow = GridView_DriverList.Rows[i];

                string ProductId = myrow.Cells[0].Text.Trim();
                int GoalCenterId = Convert.ToInt32(myrow.Cells[1].Text.Trim());
                string GoalPIPId = myrow.Cells[3].Text.Trim();

                FullDriver Fd = new FullDriver();

                switch (HiddenField_FullDriverId.Value)
                {
                    case "1": {
                        //填充当前目标成本账户的原材料投入数
                        ((TextBox)myrow.Cells[7].FindControl("TextBox_DriverAmount")).Text = Fd.MeterialMoney_TR(ProductId, Ap);

                        break;
                          }
                    case "2":
                        {
                            //填充当前目标中间体的人工投入数
                            ((TextBox)myrow.Cells[7].FindControl("TextBox_DriverAmount")).Text = Fd.HumanMoney_TR(GoalPIPId, Ap);
                            break;
                        }
                    case "0":
                        {
                            alert = "<script>alert('当前作业中心未设置动因量自动填充方式');</script>";
                           

                            break;
                        }
                
                
                
                }




            }

        }

        protected void Button_Save_Command(object sender, CommandEventArgs e)
        {
            int MyCenterId = Convert.ToInt32(HiddenField_CurrentCenterId.Value);

            var IsLock = (from a in db.TABC_JS_CostCenterToPIPPathDriver
                          where a.作业中心ID == MyCenterId
                          && a.会计期间ID == Application["accountPeriod"].ToString()
                          && a.锁定 == true
                          select a).Count();
            if (IsLock > 0)
            {

                alert = "<script>alert('当前作业中心被锁定');</script>";
                return;
            }

            if (!Page.IsValid)
            {
                alert = "<script>alert('非法数据输入,请修改');</script>";
                return;
            }


            try
            {



                //对当前列表的中间体动因记录进行插入
                for (int i = 0; i < GridView_DriverList.Rows.Count; i++)
                {
                    GridViewRow myrows = GridView_DriverList.Rows[i];

                    int GoalCenterId = Convert.ToInt32(myrows.Cells[1].Text.Trim());
                    string GoalPIPId = myrows.Cells[3].Text.Trim();
                    var IsExistRow = from a in db.TABC_JS_CostCenterToPIPPathDriver
                                     where a.会计期间ID == Application["accountPeriod"].ToString()
                                         && a.作业中心ID == MyCenterId
                                         && a.中间体ID == GoalPIPId
                                         && a.目标中心ID == GoalCenterId
                                     select a;
                    if (IsExistRow.Count() == 0)
                    {
                        TABC_JS_CostCenterToPIPPathDriver myNewRow = new TABC_JS_CostCenterToPIPPathDriver();
                        myNewRow.公司ID = "hisun";
                        myNewRow.账套ID = "001";
                        myNewRow.作业中心ID = MyCenterId;
                        myNewRow.目标中心ID = GoalCenterId;
                        myNewRow.中间体ID = GoalPIPId;
                        myNewRow.会计期间ID = Application["accountPeriod"].ToString();
                        myNewRow.录入人 = Session[ServerVars.sysSessionUserName].ToString();
                        myNewRow.系数 = Convert.ToDouble(myrows.Cells[6].Text);
                        string mynum = ((TextBox)myrows.Cells[7].FindControl("TextBox_DriverAmount")).Text;
                        myNewRow.动因量 = Convert.ToDecimal(mynum);

                        db.TABC_JS_CostCenterToPIPPathDriver.InsertOnSubmit(myNewRow);

                    }
                    else if (IsExistRow.Count() == 1)
                    {
                        var myEditRow = IsExistRow.Single();
                        myEditRow.系数 = Convert.ToDouble(myrows.Cells[6].Text);
                        string mynum = ((TextBox)myrows.Cells[7].FindControl("TextBox_DriverAmount")).Text;
                        myEditRow.动因量 = Convert.ToDecimal(mynum);
                        myEditRow.录入人 = Session[ServerVars.sysSessionUserName].ToString();

                    }

                }

                var DelUnusedPIPDriverAccount = from m in db.TABC_JS_CostCenterToPIPPathDriver
                                                join n in db.TABC_JS_ProductInProcess
                                                on m.中间体ID equals n.中间体ID
                                                where n.可用 == false
                                                && m.会计期间ID == Application["accountPeriod"].ToString()
                                                select m;
                db.TABC_JS_CostCenterToPIPPathDriver.DeleteAllOnSubmit(DelUnusedPIPDriverAccount);


                db.SubmitChanges();

                alert = "<script>alert('更新数据成功');</script>";
                MyDataBind(MyCenterId.ToString());


            }
            catch
            {
                alert = "<script>alert('更新数据失败');</script>";
            }
        }

        protected void DropDownList_CostCenter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Panel_GridList.Visible == true)
            {
                Panel_GridList.Visible = false;
            }
        }

        //定义全局变量，并对列数据绑定事件进行编程。以显示汇总数据
        decimal totalcash = 0;
        protected void GridView_DriverList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                totalcash += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "动因量"));
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "合计";
                e.Row.Cells[7].Text = totalcash.ToString("0.00");
            }
        }


    }
}
